package cn.secuber.weing.message.provider;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Handler;
import android.text.ClipboardManager;
import android.text.Selection;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import cn.secuber.weing.R;
import cn.secuber.weing.SealAppContext;
import cn.secuber.weing.libibcaxolotl.aes.AESUtil;
import cn.secuber.weing.libibcaxolotl.aes.Encrypter;
import cn.secuber.weing.message.DestructionMessage;
import cn.secuber.weing.message.PrivateMessage;
import io.rong.imkit.RongContext;
import io.rong.imkit.RongIM;
import io.rong.imkit.RongKitIntent;
import io.rong.imkit.emoticon.AndroidEmoji;
import io.rong.imkit.model.ProviderTag;
import io.rong.imkit.model.UIMessage;
import io.rong.imkit.utilities.OptionsPopupDialog;
import io.rong.imkit.widget.AutoLinkTextView;
import io.rong.imkit.widget.ILinkClickListener;
import io.rong.imkit.widget.LinkTextViewMovementMethod;
import io.rong.imkit.widget.provider.IContainerItemProvider;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;

/**
 * Created by Administrator on 2019/1/8.
 */

@ProviderTag(messageContent = PrivateMessage.class, showReadState = true)
public class PrivateMessageProvider extends IContainerItemProvider.MessageProvider<PrivateMessage>{
    private static final String TAG = "PrivateMessageItemProvider";


    private List<Integer> deleteMessage = new ArrayList<>();;

    private static class ViewHolder {
        AutoLinkTextView message;
        boolean longClick;
    }

    @Override
    public View newView(Context context, ViewGroup group) {
        View view = LayoutInflater.from(context).inflate(io.rong.imkit.R.layout.rc_item_text_message, null);

        PrivateMessageProvider.ViewHolder holder = new PrivateMessageProvider.ViewHolder();
        holder.message = (AutoLinkTextView) view.findViewById(android.R.id.text1);
        view.setTag(holder);
        return view;
    }

    @Override
    public Spannable getContentSummary(PrivateMessage data) {
        return null;
    }

    @Override
    public Spannable getContentSummary(Context context, PrivateMessage data) {
        if (data == null)
            return null;

        String content = data.getContent();
        if (content != null) {
            if (content.length() > 100) {
                content = content.substring(0, 100);
            }
            return new SpannableString(AndroidEmoji.ensure(content));
        }
        return null;
    }

    @Override
    public void onItemClick(View view, int position, PrivateMessage content, UIMessage message) {

    }

    @Override
    public void onItemLongClick(final View view, int position, final PrivateMessage content, final UIMessage message) {

        PrivateMessageProvider.ViewHolder holder = (PrivateMessageProvider.ViewHolder) view.getTag();
        holder.longClick = true;
        if (view instanceof TextView) {
            CharSequence text = ((TextView) view).getText();
            if (text != null && text instanceof Spannable)
                Selection.removeSelection((Spannable) text);
        }

        String[] items;

        long deltaTime = RongIM.getInstance().getDeltaTime();
        long normalTime = System.currentTimeMillis() - deltaTime;
        boolean enableMessageRecall = false;
        int messageRecallInterval = -1;
        boolean hasSent = (!message.getSentStatus().equals(Message.SentStatus.SENDING)) && (!message.getSentStatus().equals(Message.SentStatus.FAILED));

        try {
            enableMessageRecall = RongContext.getInstance().getResources().getBoolean(io.rong.imkit.R.bool.rc_enable_message_recall);
            messageRecallInterval = RongContext.getInstance().getResources().getInteger(io.rong.imkit.R.integer.rc_message_recall_interval);
        } catch (Resources.NotFoundException e) {
            e.printStackTrace();
        }
        if (hasSent
                && enableMessageRecall
                && (normalTime - message.getSentTime()) <= messageRecallInterval * 1000
                && message.getSenderUserId().equals(RongIM.getInstance().getCurrentUserId())
                && !message.getConversationType().equals(Conversation.ConversationType.CUSTOMER_SERVICE)
                && !message.getConversationType().equals(Conversation.ConversationType.APP_PUBLIC_SERVICE)
                && !message.getConversationType().equals(Conversation.ConversationType.PUBLIC_SERVICE)
                && !message.getConversationType().equals(Conversation.ConversationType.SYSTEM)
                && !message.getConversationType().equals(Conversation.ConversationType.CHATROOM)) {
            items = new String[] {view.getContext().getResources().getString(io.rong.imkit.R.string.rc_dialog_item_message_copy), view.getContext().getResources().getString(io.rong.imkit.R.string.rc_dialog_item_message_delete), view.getContext().getResources().getString(io.rong.imkit.R.string.rc_dialog_item_message_recall)};
        } else {
            items = new String[] {view.getContext().getResources().getString(io.rong.imkit.R.string.rc_dialog_item_message_copy), view.getContext().getResources().getString(io.rong.imkit.R.string.rc_dialog_item_message_delete)};
        }

        OptionsPopupDialog.newInstance(view.getContext(), items).setOptionsPopupDialogListener(new OptionsPopupDialog.OnOptionsItemClickedListener() {
            @Override
            public void onOptionsItemClicked(int which) {
                if (which == 0) {
                    @SuppressWarnings("deprecation")
                    ClipboardManager clipboard = (ClipboardManager) view.getContext().getSystemService(Context.CLIPBOARD_SERVICE);
                    clipboard.setText(((PrivateMessage) content).getContent());
                } else if (which == 1) {
                    RongIM.getInstance().deleteMessages(new int[] {message.getMessageId()}, null);
                } else if (which == 2) {
                    RongIM.getInstance().recallMessage(message.getMessage(), getPushContent(view.getContext(), message));
                }
            }
        }).show();
    }

    @Override
    public void bindView(final View v, int position, final PrivateMessage content, final UIMessage data) {
        PrivateMessageProvider.ViewHolder holder = (PrivateMessageProvider.ViewHolder) v.getTag();
        final AutoLinkTextView textView = holder.message;
        if (data.getMessageDirection() == Message.MessageDirection.SEND) {
            holder.message.setBackgroundResource(R.drawable.de_ic_bubble_right);
        } else {
            holder.message.setBackgroundResource(R.drawable.de_ic_bubble_left);
        }
        textView.setText(SealAppContext.getDecryptedMessage(content.getContent(),data.getMessage().getTargetId()));

        if(data.getMessage().getObjectName().equals("weing:privateMsg")){
//            RongIM.getInstance().getLatestMessages(data.getConversationType(),data.getTargetId(),1, new RongIMClient.ResultCallback<List<Message>>() {
//                @Override
//                public void onSuccess(List<Message> messages) {
//                    if(data.getMessageId()==messages.get(0).getMessageId()){
//                        deleteMessage=true;
//                    }
//                }
//                @Override
//                public void onError(RongIMClient.ErrorCode errorCode) {
//                }
//            });

            if(!RongIM.getInstance().getCurrentUserId().equals(data.getSenderUserId())){

                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {

                        if(!deleteMessage.contains(data.getMessageId())){
                            deleteMessage.add(data.getMessageId());
                            RongIM.getInstance().deleteMessages(new int[]{data.getMessageId()}, null);
                            DestructionMessage des = DestructionMessage.obtain(" 该消息已自毁 ");
                          RongIM.getInstance().insertIncomingMessage(data.getConversationType(), data.getTargetId(), data.getSenderUserId(), data.getReceivedStatus(), des, data.getSentTime() + 10, null);

                        }

                    }
                }, 7000);
            }
        }


        holder.message.setMovementMethod(new LinkTextViewMovementMethod(new ILinkClickListener() {
            @Override
            public boolean onLinkClick(String link) {
                RongIM.ConversationBehaviorListener listener = RongContext.getInstance().getConversationBehaviorListener();
                boolean result = false;
                if (listener != null) {
                    result = listener.onMessageLinkClick(v.getContext(), link);
                }
                if (listener == null || !result) {
                    String str = link.toLowerCase();
                    if (str.startsWith("http") || str.startsWith("https")) {
                        Intent intent = new Intent(RongKitIntent.RONG_INTENT_ACTION_WEBVIEW);
                        intent.setPackage(v.getContext().getPackageName());
                        intent.putExtra("url", link);
                        v.getContext().startActivity(intent);
                        result = true;
                    }
                }
                return result;
            }
        }));
    }
}

